﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Research.Kinect.Nui;

namespace KinectServer.Module
{
    /// <summary>
    /// 키넥트 디바이스를 표현하는 객체
    /// </summary>
    public class Kinect : IDisposable
    {
        public Runtime Nui { get; private set; }
        
        private bool _isRunning;

        public Kinect()
        {
            Nui = new Runtime();
        }

        public void Start()
        {
            if (this._isRunning == true) return;
           
            /* 초기화 시작 */

            try
            {
                Nui.Initialize(RuntimeOptions.UseDepthAndPlayerIndex | RuntimeOptions.UseSkeletalTracking | RuntimeOptions.UseColor);
            }
            catch (InvalidOperationException)
            {
                System.Windows.MessageBox.Show("Runtime initialization failed. Please make sure Kinect device is plugged in.");
                Log.e(this, "키넥트 연결 실패!: 키넥트가 연결되었나요?");
                return;
            }

            try
            {
                Nui.VideoStream.Open(ImageStreamType.Video, 2, ImageResolution.Resolution640x480, ImageType.Color);
                Nui.DepthStream.Open(ImageStreamType.Depth, 2, ImageResolution.Resolution320x240, ImageType.DepthAndPlayerIndex);
            }
            catch (InvalidOperationException)
            {
                System.Windows.MessageBox.Show("Failed to open stream. Please make sure to specify a supported image type and resolution.");
                Log.e(this, "키넥트 연결 실패!: 출력할 이미지 설정이 이상한것 같네요");
                return;
            }

            Log.i(this, "키넥트가 연결되었습니다.");

            /* 초기화 끝 */

            this._isRunning = true;
        }

        public void Stop()
        {   
            this.Dispose();
            Log.d(this.GetType(), "키넥트 연결을 종료합니다.");
        }

        public void Dispose()
        {
            this._isRunning = false;
            Nui.Uninitialize();
        }

        internal void CameraUp(int p)
        {
            try
            {   
                Nui.NuiCamera.ElevationAngle += Math.Abs(p);
            }
            catch (Exception)
            {

            }

            Log.i(this, "카메라 업 - " + Nui.NuiCamera.ElevationAngle);
        }

        internal void CameraDown(int p)
        {
            try
            {   
                Nui.NuiCamera.ElevationAngle -= Math.Abs(p);
            }
            catch (Exception)
            {
               
            }

            Log.i(this, "카메라 다운 - " + Nui.NuiCamera.ElevationAngle);
        }

        internal void CameraZero()
        {
            try
            {
                Nui.NuiCamera.ElevationAngle = 0;
            }
            catch (Exception)
            {

            }

            Log.i(this, "카메라 수평 - " + Nui.NuiCamera.ElevationAngle);
        }
    }
}
